namespace Digitalmes.Application.Sys.Users.Commands;

/// <summary>
/// 更新用户信息命令。
/// </summary>
public record UpdateUserCommand(long Id, SysUserDto User) : IRequest<IResult<bool>>;

internal sealed class UpdateUserCommandHandler(IRepository<SysUser> repo) : IRequestHandler<UpdateUserCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
    {
        var user = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (user == null)
        {
            return Result.Failure("未找到要更新的账号");
        }

        user.Realname = request.User.Realname;
        user.Phone = request.User.Phone;
        user.Email = request.User.Email;
        user.Gender = request.User.Gender;
        user.OrgId = request.User.OrgId;
        user.PosId = request.User.PosId;
        user.JobNum = request.User.JobNum;
        user.PosLevel = request.User.PosLevel;
        user.ServiceDate = request.User.ServiceDate;
        user.Remark = request.User.Remark;

        var ok = await repo.UpdateAsync(user, m => new
        {
            m.Realname,
            m.Phone,
            m.Email,
            m.Gender,
            m.OrgId,
            m.PosId,
            m.JobNum,
            m.PosLevel,
            m.ServiceDate,
            m.Remark,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
